<template>
  <cl-page
    class="booking-page"
    :back-top="true"
  >
    <view
      v-if="work"
      class="booking-summary"
    >
      <cl-image
        :src="work.coverUrl"
        :height="220"
        :width="220"
        :pt="{ className: 'booking-summary__cover' }"
      />
      <view class="booking-summary__info">
        <text class="booking-summary__title">{{ work.title }}</text>
        <text class="booking-summary__subtitle">{{ work.subtitle }}</text>
        <view class="booking-summary__meta">
          <cl-tag
            type="primary"
          >{{ work.priceRange }}</cl-tag>
          <!-- <cl-tag
            type="primary"
          >{{ work.duration }}</cl-tag> -->
        </view>
      </view>
    </view>

    <view class="form">
      <view class="form-item">
        <text class="form-label">预约人姓名</text>
        <cl-input
          v-model="formState.customerName"
          placeholder="请输入姓名"
          clearable
          prefix-icon="user-line"
        />
      </view>

      <view class="form-item">
        <text class="form-label">联系方式</text>
        <cl-input
          v-model="formState.contactPhone"
          placeholder="请输入手机号"
          type="number"
          clearable
          prefix-icon="phone-line"
        />
      </view>

      <view class="form-item form-item--calendar">
        <text class="form-label">预约日期</text>
        <text
          v-if="formState.preferredDate"
          class="selected-date"
        >已选择: {{ formState.preferredDate }}</text>
      </view>

      <view class="calendar-container">
        <cl-calendar
          v-model="formState.preferredDate"
          mode="single"
          :start="tomorrowDate"
          :date-config="dateConfig"
          bg-selected-color="#5B8CFF"
          text-selected-color="#ffffff"
          text-today-color="#5B8CFF"
          :cell-height="60"
          @change="handleDateChange"
        />
      </view>

      <view class="form-item form-item--textarea">
        <text class="form-label">备注需求</text>
        <cl-textarea
          v-model="formState.remark"
          :maxlength="200"
          placeholder="请描述想要的拍摄风格、人数或其他补充信息"
          border
          show-word-limit
        />
      </view>
    </view>

    <view class="booking-footer">
      <cl-button
        type="primary"
        color="#fff"
        class="booking-submit"
        :loading="submitting"
        rounded
        @tap="handleSubmit"
      >
        提交预约
      </cl-button>
    </view>
  </cl-page>
</template>

<script setup>
import { ref, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { createBooking, fetchWorkDetail, fetchAvailableDates } from "@/services/gallery";

const formState = ref({
  workId: "",
  customerName: "",
  contactPhone: "",
  preferredDate: "",
  remark: ""
});

const work = ref(null);
const submitting = ref(false);
const availableDates = ref([]);

const tomorrowDate = computed(() => {
  const now = new Date();
  const currentHour = now.getHours();

  // 如果当前时间已过22点，从明天开始
  // 如果未过22点，从今天开始
  const startDate = currentHour >= 22 ? new Date(now.getTime() + 24 * 60 * 60 * 1000) : now;

  const year = startDate.getFullYear();
  const month = String(startDate.getMonth() + 1).padStart(2, "0");
  const day = String(startDate.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
});

const dateConfig = computed(() => {
  const now = new Date();
  const currentHour = now.getHours();
  const today = formatDate(now);

  // 使用后端返回的可用日期数据
  return availableDates.value.map(item => {
    // 如果是今天且已过22点，禁用该日期
    const isTodayAfter22 = item.date === today && currentHour >= 22;

    return {
      date: item.date,
      bottomText: isTodayAfter22 ? "已过期" : (item.bottomText || (item.isAvailable ? "可预约" : "已满")),
      color: isTodayAfter22 ? "#999999" : (item.color || (item.isAvailable ? "#52c41a" : "#ff4d4f")),
      disabled: isTodayAfter22 || !item.isAvailable
    };
  });
});

onLoad(async(options) => {
  const workId = options?.workId;
  if (workId) {
    formState.value.workId = workId;
  }
  
  try {
    // 并行请求作品详情和可用日期
    const now = new Date();
    const currentHour = now.getHours();

    // 如果已过22点，从明天开始获取；否则从今天开始
    const startDateObj = currentHour >= 22 ? new Date(now.getTime() + 24 * 60 * 60 * 1000) : now;
    const startDate = formatDate(startDateObj);

    const endDate = new Date(startDateObj);
    endDate.setDate(endDate.getDate() + 30); // 获取未来30天的数据
    const endDateStr = formatDate(endDate);
    
    const promises = [
      workId ? fetchWorkDetail(workId) : Promise.resolve(null),
      fetchAvailableDates({ 
        startDate, 
        endDate: endDateStr,
        workId: workId || undefined
      })
    ];
    const [workData, datesData] = await Promise.all(promises);
    
    if (workData) {
      work.value = workData;
    }
    if (datesData) {
      availableDates.value = datesData;
    }
  } catch (error) {
    console.error("数据加载失败:", error.message);
    uni.showToast({ title: error.message || "数据加载失败", icon: "none" });
  }
});

function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

function handleDateChange(dates) {
  if (dates && dates.length > 0) {
    formState.value.preferredDate = dates[0];
  }
}

async function handleSubmit() {
  if (!formState.value.customerName) {
    uni.showToast({ title: "请输入姓名", icon: "none" });
    return;
  }
  if (!formState.value.contactPhone) {
    uni.showToast({ title: "请输入联系方式", icon: "none" });
    return;
  }
  if (!formState.value.preferredDate) {
    uni.showToast({ title: "请选择预约日期", icon: "none" });
    return;
  }
  if (!formState.value.workId) {
    uni.showToast({ title: "缺少作品信息", icon: "none" });
    return;
  }

  // 打印表单数据
  console.log("=== 预约表单数据 ===");
  console.log("作品ID:", formState.value.workId);
  console.log("预约人姓名:", formState.value.customerName);
  console.log("联系方式:", formState.value.contactPhone);
  console.log("预约日期:", formState.value.preferredDate);
  console.log("备注需求:", formState.value.remark);
  console.log("完整表单数据:", formState.value);
  console.log("==================");

  submitting.value = true;
  try {
    await createBooking({ ...formState.value });
    uni.showToast({ title: "预约成功", icon: "success" });
    setTimeout(() => {
      uni.navigateBack({ delta: 1 });
    }, 1500);
  } catch (error) {
    uni.showToast({ title: error.message || "预约失败", icon: "none" });
  } finally {
    submitting.value = false;
  }
}
</script>

<style scoped lang="scss">
.booking-page {
  min-height: 100vh;
  background: #f6f7fb;
  padding-bottom: 160rpx;
}

.booking-summary {
  display: flex;
  padding: 32rpx;
  gap: 24rpx;
}

.booking-summary__cover {
  border-radius: 24rpx;
}

.booking-summary__info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.booking-summary__title {
  font-size: 34rpx;
  font-weight: 600;
  color: #222;
}

.booking-summary__subtitle {
  font-size: 26rpx;
  color: #666;
}

.booking-summary__meta {
  margin-top: 10rpx;
  display: flex;
  gap: 16rpx;
}

.form {
  margin: 0 32rpx;
  padding: 32rpx;
  background: #fff;
  border-radius: 28rpx;
  box-shadow: 0 12rpx 24rpx rgba(0, 0, 0, 0.06);
  display: flex;
  flex-direction: column;
  gap: 28rpx;
  padding-bottom: 9vh;
}

.form-item {
  display: flex;
  align-items: center;
  gap: 24rpx;
}

.form-item--textarea {
  align-items: flex-start;
  flex-direction: column;
  width: 100%;
  box-sizing: border-box;

  :deep(.cl-textarea) {
    position: relative;
    width: 100%;
    box-sizing: border-box;

    .cl-text {
      position: absolute;
      right: 16rpx;
      bottom: 16rpx;
    }
  }
}

.form-item--calendar {
  flex-direction: column;
  align-items: flex-start;
}

.selected-date {
  font-size: 26rpx;
  color: #666;
  margin-top: 8rpx;
}

.calendar-container {
  width: 100%;
  margin-top: 16rpx;
  padding: 24rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);

  :deep(.cl-calendar) {
    background: transparent;
  }

  :deep(.cl-calendar__view-cell) {
    border-radius: 8rpx;
    transition: all 0.2s ease;

    &.is-selected {
      background-color: #5B8CFF !important;
      transform: scale(1.05);

      .cl-text {
        color: #fff !important;
      }
    }

    &.is-today {
      border: 2rpx solid #5B8CFF;
    }

    &.is-disabled {
      background-color: #f5f5f5;
      cursor: not-allowed;
      opacity: 0.6;
    }
  }
}

.form-label {
  font-size: 28rpx;
  color: #333;
  min-width: 200rpx;
}

.booking-footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 20rpx 32rpx;
  background: #fff;
  box-shadow: 0 -8rpx 24rpx rgba(0, 0, 0, 0.08);
}

.booking-submit {
  width: 100%;
}
</style>
